package com.gm.controller.user;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.gm.common.Pager;
import com.gm.controller.dto.LoginUser;
import com.gm.model.Base.Const;
import com.gm.model.po.Role;
import com.gm.model.po.User;
import com.gm.model.vo.ResMsg;
import com.gm.service.user.RightService;
import com.gm.service.user.RoleSerivce;
import com.gm.service.user.UserService;
import com.gm.sys.enums.SystemErrorCode;
import com.gm.tools.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户模块
 * Created by yangxing on 2017/6/8.
 */

@Controller
@RequestMapping("user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RightService rightService;

    @Autowired
    private RoleSerivce roleSerivce;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg login(@Valid LoginUser logiUser, BindingResult result, HttpServletRequest request){

        logger.info("Method[login], 参数[{}]", logiUser.toString());

        ResMsg msg = new ResMsg();
        if (result.hasErrors()) {
            msg.setError(result.getAllErrors().get(0).getDefaultMessage());
            logger.error("Method[login], Error[{}]", result.getAllErrors().get(0).getDefaultMessage());
        } else {
            User user = userService.userLogin(logiUser.getUsername(), logiUser.getPassword());
            if (null == user) {
                msg.setError(SystemErrorCode.username_error.getName());
            }else{
                if (!Md5Utils.encrypMD5_32(logiUser.getPassword()).equals(user.getPwd())) {
                    msg.setError(SystemErrorCode.password_error.getName());
                    logger.error("Method[login], Error[{}]", SystemErrorCode.password_error.getName());
                } else{
                    msg.setStatus(Const.RES_OK);
                    request.getSession().setAttribute("user",user);
                    request.getSession().setAttribute("rightList",rightService.getRoleAuthority(user.getRoles()));
                }
            }

        }
        logger.info("Method[login], rlt.status[{}]", msg.getStatus());
        return msg;
    }

    @RequestMapping("index.web")
    public ModelAndView index(HttpServletRequest request){
        ModelAndView view= new ModelAndView("");
        view.setViewName("/index.jsp");
        return view;
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("logout.do")
    public ModelAndView logout(HttpServletRequest request){
        ModelAndView view= new ModelAndView("redirect:/");
        request.getSession().removeAttribute("user");
        return view;
    }


    @RequestMapping("gotoAddUser.web")
    public ModelAndView gotoAddUser(){
        ModelAndView view= new ModelAndView();
        List<Role> roleList = roleSerivce.getALlRole();
        view.addObject("roleList", roleList);
        view.setViewName("/user/addUser.jsp");
        return view;
    }

    @RequestMapping("addUser.web")
    public ModelAndView addUser(User user,Integer roleId,RedirectAttributes attr){
        ModelAndView view= new ModelAndView();
        user.setRoles(roleId.toString());
        user.setPwd(Md5Utils.encrypMD5_32(user.getPwd()));
        int ret = userService.addUser(user);
        if(ret==1){
            attr.addFlashAttribute("msg", "添加成功");
        }else{
            attr.addFlashAttribute("msg", "添加失败");
        }
        view.setViewName("redirect:/user/userList.web");
        return view;
    }

    @RequestMapping("gotoUpdateUser.web")
    public ModelAndView gotoUpdateUser(Integer userId,Integer currentPage){
        ModelAndView view= new ModelAndView();
        User user = userService.selectByPrimaryKey(userId);
        List<Role> roleList = roleSerivce.getALlRole();
        view.addObject("roleList", roleList);
        view.addObject("currentPage", currentPage);
        view.addObject("user", user);
        view.setViewName("/user/updateUser.jsp");
        return view;
    }

    @RequestMapping("updateUser.web")
    public ModelAndView updateUser(User user,Integer roleId,Integer currentPage,RedirectAttributes attr){
        ModelAndView view= new ModelAndView();
        user.setRoles(roleId.toString());
        int ret = userService.updateUser(user);
        if(ret==1){
            attr.addFlashAttribute("msg", "修改成功");
        }else{
            attr.addFlashAttribute("msg", "添修改失败");
        }
        view.addObject("currentPage", currentPage);
        view.setViewName("redirect:/user/userList.web");
        return view;
    }

    @RequestMapping("userList.web")
    public ModelAndView userList(Pager pager){
        ModelAndView view= new ModelAndView();
        List userList = userService.getUsereList(pager);
        PageList pageList = (PageList)userList;
        Paginator paginator = pageList.getPaginator();
        view.addObject("userList", userList);
        view.addObject("paginator", paginator);
        view.setViewName("/user/user.jsp");
        return view;
    }

    @RequestMapping("deleteUser.web")
    public ModelAndView deleteUser(Integer userId,Integer currentPage,RedirectAttributes attr){
        ModelAndView view= new ModelAndView();
        int ret = userService.deleteUser(userId);
        if(ret==1){
            attr.addFlashAttribute("msg", "删除成功");
        }else{
            attr.addFlashAttribute("msg", "删除失败");
        }
        Pager pager = new Pager();
        pager.setCurrentPage(currentPage);
        List userList = userService.getUsereList(pager);
        if(userList.size() == 0){
            currentPage = currentPage -1;
        }
        if(currentPage==0)currentPage=1;
        view.addObject("currentPage", currentPage);
        view.setViewName("redirect:/user/userList.web");
        return view;
    }
}
